<script setup lang="ts">
import { computed, reactive, watch } from 'vue';
import { fetchCreateGameRecordDetail, fetchUpdateGameRecordDetail } from '@/service/api/games/game-record-detail';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';

defineOptions({
  name: 'GameRecordDetailOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.Games.GameRecordDetail | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});


const { formRef, validate, restoreValidation } = useNaiveForm();
const { createRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: '新增游戏记录详情',
    edit: '编辑游戏记录详情'
  };
  return titles[props.operateType];
});

type Model = Api.Games.GameRecordDetailOperateParams;

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
      recordId: undefined,
      userId: undefined,
      gameCode: '',
      emojiUnicode: '',
      emojiChar: '',
      eliminatedCount: undefined,
      eliminatedTime: undefined,
  };
}

type RuleKey = Extract<
  keyof Model,
  | 'detailId'
  | 'recordId'
  | 'userId'
  | 'gameCode'
  | 'emojiUnicode'
  | 'emojiChar'
>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  detailId: createRequiredRule('详情ID不能为空'),
  recordId: createRequiredRule('游戏记录ID不能为空'),
  userId: createRequiredRule('用户ID不能为空'),
  gameCode: createRequiredRule('游戏编码不能为空'),
  emojiUnicode: createRequiredRule('Emoji的Unicode编码不能为空'),
  emojiChar: createRequiredRule('Emoji字符不能为空'),
};

function handleUpdateModelWhenEdit() {
  if (props.operateType === 'add') {
    Object.assign(model, createDefaultModel());
    return;
  }

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, props.rowData);
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();

  const { detailId, recordId, userId, gameCode, emojiUnicode, emojiChar, eliminatedCount, eliminatedTime } = model;

  // request
  if (props.operateType === 'add') {
    const { error } = await fetchCreateGameRecordDetail({ recordId, userId, gameCode, emojiUnicode, emojiChar, eliminatedCount, eliminatedTime });
    if (error) return;
  }

  if (props.operateType === 'edit') {
    const { error } = await fetchUpdateGameRecordDetail({ detailId, recordId, userId, gameCode, emojiUnicode, emojiChar, eliminatedCount, eliminatedTime });
    if (error) return;
  }

  window.$message?.success($t('common.updateSuccess'));
  closeDrawer();
  emit('submitted');
}

watch(visible, () => {
  if (visible.value) {
    handleUpdateModelWhenEdit();
    restoreValidation();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" :title="title" display-directive="show" :width="800" class="max-w-90%">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules">
        <NFormItem label="游戏记录ID" path="recordId">
          <NInput v-model:value="model.recordId" placeholder="请输入游戏记录ID" />
        </NFormItem>
        <NFormItem label="用户ID" path="userId">
          <NInput v-model:value="model.userId" placeholder="请输入用户ID" />
        </NFormItem>
        <NFormItem label="游戏编码" path="gameCode">
          <NInput v-model:value="model.gameCode" placeholder="请输入游戏编码" />
        </NFormItem>
        <NFormItem label="Emoji的Unicode编码" path="emojiUnicode">
          <NInput v-model:value="model.emojiUnicode" placeholder="请输入Emoji的Unicode编码" />
        </NFormItem>
        <NFormItem label="Emoji字符" path="emojiChar">
          <NInput v-model:value="model.emojiChar" placeholder="请输入Emoji字符" />
        </NFormItem>
        <NFormItem label="本局消灭数量" path="eliminatedCount">
          <NInput v-model:value="model.eliminatedCount" placeholder="请输入本局消灭数量" />
        </NFormItem>
        <NFormItem label="消灭时间" path="eliminatedTime">
          <NDatePicker
            v-model:formatted-value="model.eliminatedTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            clearable
          />
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
